import {createRouter, createWebHistory} from 'vue-router';
import { routes } from './route';
import {filterMenus, useMenuStore} from "../store/menu";
import {useContextStore} from "../store/context";
import {getUserInfo} from "../mock";

const router = createRouter({
  history: createWebHistory(),
  routes,
  strict: true,
});

const whiteRouteNames = ['Login'];

router.beforeEach(async (to, from, next) => {
  // console.log('beforeEach');
  if (whiteRouteNames.includes(to.name as string)) {
    next();
  } else {
    const contextStore = useContextStore();
    // token 存在 ?
    if (true) {
      if (contextStore.userInfo) {
        next();
      } else {
        try {
          const userInfo = await getUserInfo();
          contextStore.setUserInfo(userInfo);
          const menuStore = useMenuStore();
          menuStore.setAllMenus(filterMenus(routes));
          next();
        } catch (error) {
          console.error('Get context error>>', error);
          next('/login');
        }
      }
    } else {
      next('/login');
    }
  }
});

export { routes, router }
